<template>
    <div class="table-wrapped">
        <div class="search-wrapped">
            <el-form :inline="true" :model="searchFrom" class="demo-form-inline">
                <div class="first-wrapped">
                    <el-form-item label="姓名:">
                        <el-input v-model="searchFrom.name" placeholder="请输入姓名"></el-input>
                    </el-form-item>
                    <el-form-item label="部门:">
                        <el-select v-model="searchFrom.deptId" placeholder="请选择">
                            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <div>
                    <el-form-item label="入职时间:">
                        <span>开始时间:</span>
                        <el-date-picker v-model="searchFrom.begin" type="date" placeholder="选择日期"
                            format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <span>结束时间:</span>
                        <el-date-picker v-model="searchFrom.end" type="date" placeholder="选择日期"
                            format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <template>
                            <el-button type="primary" size="mini" @click="onSubmit(); clearSearchFrom()"><i
                                    class="el-icon-search"></i>查询</el-button>
                            <el-button type="success" size="mini" @click="registerFormVisible = true"><i
                                    class="el-icon-circle-plus"></i>添加</el-button>
                        </template>
                    </el-form-item>
                </div>
            </el-form>
        </div>
        <el-table :data="tableData" height="350" border style="width: 100%">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="username" label="账号" width="114">
            </el-table-column>
            <el-table-column prop="name" label="姓名" width="100">
            </el-table-column>
            <el-table-column prop="password" label="密码" width="100">
            </el-table-column>
            <el-table-column prop="gender" label="性别" width="100">
                <template slot-scope="scope">
                    <span style="margin-left: 10px">{{ scope.row.gender === 1 ? '男' : '女' }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="image" label="头像" width="100">
                <template slot-scope="scope">
                    <img :src="scope.row.image" min-width="80" height="80" />
                </template>
            </el-table-column>
            <el-table-column prop="jobName" label="职位" width="100">
            </el-table-column>
            <el-table-column prop="deptName" label="部门" width="100">
            </el-table-column>
            <el-table-column prop="entrydate" label="入职时间" width="120">
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="160">
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="160">
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" icon="el-icon-edit" circle
                        @click="update(scope.row)"></el-button>
                    <el-button type="danger" size="mini" icon="el-icon-delete" circle
                        @click="deleteUser(scope.row)"></el-button>
                    <el-button type="danger" icon="el-icon-refresh" size="mini" circle
                        @click="resetPassword(scope.row)"></el-button>
                </template>
            </el-table-column>
            <template slot="empty">
                <el-empty description="没有数据"></el-empty>
            </template>
        </el-table>
        <div class="block">
            <el-pagination background @current-change="handleCurrentChange" :current-page.sync="searchFrom.currentPage"
                :page-size="searchFrom.pageSize" layout="total, prev, pager,jumper, next" :total="total">
            </el-pagination>
        </div>
        <el-dialog title="员工信息" :visible.sync="dialogFormVisible">
            <div class="info-wrapped">
                <el-form :model="UserInfoForm">
                    <el-form-item label="姓名:" label-width="100px">
                        <el-input v-model="UserInfoForm.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="密码:" label-width="100px">
                        <el-input v-model="UserInfoForm.password" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="职业:" label-width="100px">
                        <el-select v-model="UserInfoForm.job" placeholder="请选择">
                            <el-option v-for="item in jobs" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="部门:" label-width="100px">
                        <el-select v-model="UserInfoForm.deptId" placeholder="请选择">
                            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="dialogFormVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="confirmUpdate()">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="添加员工" :visible.sync="registerFormVisible">
            <div class="add-wrapped">
                <el-form :model="registerForm" :rules="rules" ref="addFrom">
                    <el-form-item label="账号:" label-width="100px" prop="username">
                        <el-input v-model="registerForm.username" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="姓名:" label-width="100px">
                        <el-input v-model="registerForm.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="部门:" label-width="100px">
                        <el-select v-model="registerForm.deptId" placeholder="请选择">
                            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button size="small" @click="registerFormVisible = false; clearRegisterFrom()">取 消</el-button>
                    <el-button size="small" type="primary" @click="register('addFrom')">确 定</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { AddUserServer, DeleteUserServer, GetAllDept, OnlyUserServer, 
    PageGetUserServer, ResetPassword, UpdateUserServer,GetAllJobs } from '@/api/user';
//自定义账号唯一

let onlyUserName = async (rule, value, callback) => {
    let res = await OnlyUserServer(value)
    if (res.code == 0) {
        callback(new Error('用户名已存在'))
    } else {
        callback();
    }
}
export default {
    data() {
        return {
            searchFrom: {
                name: '',
                deptId: '',
                begin: '',
                end: '',
                pageSize: 10,
                currentPage: 1
            },
            //部门全部分类
            options: [],
            jobs: [],
            total: 0,
            dialogFormVisible: false,
            registerFormVisible: false,
            UserInfoForm: {
                username: '',
                name: '',
                password: '',
                deptId: '',
                job: ''
            },
            //添加用户菜单
            registerForm: {
                username: '',
                name: '',
                deptId: '',
            },
            tableData: [],
            //异步验证账号是否存在
            rules: {
                username: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                    { validator: onlyUserName, message: '用户名已存在', trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        //清空表单数据
        clearRegisterFrom() {
            this.registerForm = {
                username: '',
                name: '',
                password: '',
                deptId: '',
            }
        },
        //清空搜索字段内容
        clearSearchFrom() {
            this.searchFrom = {
                name: '',
                deptId: '',
                begin: '',
                end: '',
                pageSize: 10,
                currentPage: 1
            }
        },
        async getDepartments() {
            let res = await GetAllDept()
            if (res.code == 1) {
                this.options = res.data
                console.log(this.options)
            } else {
                this.$message({
                    showClose: true,
                    message: '获取部门分类失败',
                    type: 'error'
                });
            }
        },
        async getAllUser() {
            let res = await PageGetUserServer(this.searchFrom)
            if (res.code == 1) {
                this.tableData = res.data.records
                this.total = res.data.total
                console.log(this.tableData)
            } else {
                this.$message({
                    showClose: true,
                    message: '获取用户数据失败',
                    type: 'error'
                });
            }
        },
        handleCurrentChange(val) {
            this.searchFrom.currentPage = val
            this.getAllUser()
        },
        async onSubmit() {
            let res = await PageGetUserServer(this.searchFrom)
            if (res.code == 1) {
                this.tableData = res.data.records
                this.total = res.data.total
                console.log(this.tableData)
            } else {
                this.$message({
                    showClose: true,
                    message: '获取分页查询失败',
                    type: 'error'
                });
            }
        },
        update(row) {
            let option = this.options.find(option => option.name === row.deptName)
            let job = this.jobs.find(job => job.name === row.jobName)
            if (option !== undefined) {
                option = option.id
            } else {
                option = null
            }
            if (job !== undefined) {
                job = job.id
            } else {
                job = null
            }
            this.UserInfoForm = {
                username: row.username,
                name: row.name,
                deptId: option,
                password: row.password,
                job: job
            }
            this.dialogFormVisible = true
        },
        //确定跟新员工信息
        async confirmUpdate() {
            let res = await UpdateUserServer(this.UserInfoForm)
            if (res.code == 1) {
                this.$message({
                    type: 'success',
                    message: '修改成功!'
                });
                this.dialogFormVisible = false
                this.getAllUser()
            } else {
                this.$message({
                    type: 'error',
                    message: '修改失败!'
                });
                this.dialogFormVisible = false
            }
        },
        async getJobs() {
            let res = await GetAllJobs()
            if (res.code == 1) {
                this.jobs = res.data
                console.log(this.jobs)
            } else {
                this.$message({
                    showClose: true,
                    message: '获取职业分类失败',
                    type: 'error'
                });
            }
        },
        deleteUser(row) {
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                console.log(row.username)
                let res = await DeleteUserServer({ 'username': row.username })
                if (res.code == 1) {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getAllUser()
                } else {
                    this.$message({
                        type: 'error',
                        message: res.msg ? res.msg : '删除失败！'
                    });
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        async register(addFrom) {
            this.$refs[addFrom].validate(async (valid) => {
                if (valid) {
                    let res = await AddUserServer(this.registerForm)
                    if (res.code == 1) {
                        this.$message({
                            type: 'success',
                            message: '添加员工成功!'
                        });
                        this.getAllUser()
                    } else {
                        this.$message({
                            type: 'error',
                            message: '添加员工失败!'
                        });
                    }
                    this.registerFormVisible = false
                    this.clearRegisterFrom()
                }
            })

        },
        //重置密码
        async resetPassword(row) {
            let res = await ResetPassword({ 'username': row.username })
            if (res.code == 1) {
                this.$message({
                    type: 'success',
                    message: '密码已重置!'
                });
                this.getAllUser()
            }
        }
    },
    mounted() {
        this.getDepartments()
        this.getAllUser()
        this.getJobs()
    },
}
</script>

<style lang="less" scoped>
.block {
    display: flex;
    flex-direction: row-reverse;
}
.first-wrapped{
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
}
.search-wrapped {
    margin-left: 2%;
    display: flex;
    flex-direction: row;

}

.el-range-editor.el-input__inner {
    padding: 0;
    height: 30px;
}

.dialog-footer {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: row;
}

.info-wrapped {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
}

.add-wrapped {
    display: flex;
    flex-direction: column;
    align-items: center;
}

:deep(.cell) {
    display: flex;
    justify-content: center;
    align-items: center;
}

:deep(.el-table th) {
    text-align: center;
}

:deep(.el-input__inner) {
    height: 30px;
    margin-left: 1%;
}

:deep(.el-dialog__body) {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}
</style>